/**
 * 尊敬的用户，你好：
 * 页面 JS 面板是高阶用法，一般不建议普通用户使用，如需使用，请确保你具备研发背景，能够自我排查问题。
 * 我们可以用 JS 面板来开发一些定制化功能，比如：调用 API 接口、自定义动作执行等等。
 */

// 页面渲染完成时调用
export function didMount() {
    console.log("「页面 JS」：当前页面地址 " + location.href);
    queryRecData.call(this);
}

/**
 * 查询记录数据
 */
export function queryRecData() {
    const self = this;

    // 获取级联选择器的值（区域）
    var regionValues = self.$$("csdn_form_field_cascader_a2di41").$$getValue() || [];
    var regionId = regionValues.length > 0 ? regionValues[regionValues.length - 1] : '';
    var regionLevel = regionValues.length > 0 ? regionValues.length - 1 : '';

    // 获取日期选择器的值
    var datePicker = self.$$("csdn_form_custom_date_ao9h89");
    var startTime = null;
    var endTime = null;
    if (datePicker && datePicker.currentTime) {
        startTime = datePicker.currentTime.start.format('YYYY-MM-DD 00:00:00');
        endTime = datePicker.currentTime.end.format('YYYY-MM-DD 23:59:59');
    }

    // 配置每个类别对应的数据源ID及处理函数
    var categoryMap = {
        recOverview: {
            ddcatId: "a7d4f3a4-9a0a-412a-9377-8db88d7c94c9",
            handler: handleRecOverview
        },
        recDomainOverview: {
            ddcatId: "ebfa3e82-fcc5-41b1-aff8-79a9216b197c",
            handler: handleRecDomainOverview
        },
        recTypeStat: {
            ddcatId: "b2112524-e9e4-4dff-bfe6-af43d3733ea0",
            handler: handleRecTypeStat
        },
        recSourceStat: {
            ddcatId: "2cdc3f56-5c6a-410f-a397-f16401271322",
            handler: handleRecSourceStat
        },
        recWarn: {
            ddcatId: "707ed14f-522b-4868-9753-b4ffe2cb1492",
            handler: handleRecWarn
        }
    };

    // 循环初始化每个类别
    Object.keys(categoryMap).forEach(function (category) {
        var { ddcatId, handler } = categoryMap[category];
        initCategory(self, ddcatId, startTime, endTime, regionLevel, regionId, handler);
    });
}

/**
 * 通用初始化方法
 */
function initCategory(self, ddcatId, startTime, endTime, regionLevel, regionId, handler) {
    getRecData(self, ddcatId, startTime, endTime, regionLevel, regionId)
        .then(function (res) {
            console.log(`数据获取成功: ${ddcatId}`);
            handler(self, res);
        })
        .catch(function (err) {
            console.error(`数据获取失败: ${ddcatId}`, err);
        });
}

/**
 * 案件概况处理函数
 */
function handleRecOverview(self, data) {
    console.log("处理案件概况:", data);
    let recAllEle = self.$$("text_eoo7w7");
    let recUnHandleCountEle = self.$$("text_hdh5r6");
    let recHandleCountEle = self.$$("text_g6l0vs");
    let recHandleRateEle = self.$$("text_25epjh");
    let recUnHandleValue = parseInt(data[0].recCount) - parseInt(data[0].handleCount);

    recAllEle.$$setValue(data[0].recCount);
    recUnHandleCountEle.$$setValue(recUnHandleValue);
    recHandleCountEle.$$setValue(data[0].handleCount);
    recHandleRateEle.$$setValue(data[0].handleRate + " %");
}

/**
 * 重点领域案件概况处理函数
 */
function handleRecDomainOverview(self, data) {
    console.log("处理重点领域案件概况:", data);
    let reecDomainEle = self.$$("csdn_page_indicator_cchc2e");
    const result = data ? data.map(item => ({
        name: item.sourceCode,
        text: item.sourceName,
        value: item.total
    })) : [];
    reecDomainEle.data.props.dataSource.options = result || [];
}

/**
 * 案件类型处理函数
 */
function handleRecTypeStat(self, data) {
    console.log("处理案件类型:", data);
    let recTypeStat1 = self.$$("csdn_page_indicator_13ei00");
    let recTypeStat2 = self.$$("csdn_page_indicator_647w50");
    let result1 = [
        {
            "name": "1",
            "text": "普通程序",
            "value": data[0].normalCount,
            "checked": false
        },
        {
            "name": "2",
            "text": "简易程序",
            "value": data[0].easyCount,
            "checked": false
        },
        {
            "name": "3",
            "text": "罚款案件",
            "value": data[0].punishCount,
            "checked": false
        }
    ];

    let result2 = [
        {
            "name": "1",
            "text": "罚款金额",
            "value": data[0].punishMoney,
            "unit": "万元",
            "checked": false
        },
        {
            "name": "2",
            "text": "已收罚款",
            "value": data[0].paidMoney,
            "unit": "万元",
            "checked": false
        },
        {
            "name": "3",
            "text": "应收罚款",
            "value": parseInt(data[0].punishMoney) - parseInt(data[0].paidMoney),
            "unit": " 万元",
            "checked": false
        }
    ];

    recTypeStat1.data.props.dataSource.options = result1 || [];
    recTypeStat2.data.props.dataSource.options = result2 || [];

}

/**
 * 案件来源处理函数
 */
function handleRecSourceStat(self, data) {
    console.log("处理案件来源:", data);

    let numDeptEle  = self.$$("text_6yz15m"); // 部门移送
    let numComplaintEle = self.$$("text_2uxexa"); // 投诉举报
    let numSuperiorEle = self.$$("text_xvivb");  // 上级交办
    let numInspectionEle = self.$$("text_6yw9ax"); // 巡查发现
    const sourceDict = {
        "1": "巡查发现",
        "2": "上级交办",
        "3": "投诉举报",
        "4": "部门移送"
    };

    const dataMap = {};
    data.forEach(item => {
        dataMap[item.sourceCode] = parseInt(item.total, 10);
    });

    const normalized = Object.keys(sourceDict).map(code => ({
        sourceCode: code,
        sourceName: sourceDict[code],
        total: dataMap[code] || 0
    }));


    numInspectionEle.$$setValue(normalized.find(x => x.sourceCode === "1").total); // 巡查发现
    numSuperiorEle.$$setValue(normalized.find(x => x.sourceCode === "2").total);   // 上级交办
    numComplaintEle.$$setValue(normalized.find(x => x.sourceCode === "3").total);  // 投诉举报
    numDeptEle.$$setValue(normalized.find(x => x.sourceCode === "4").total);       // 部门移送
}

/**
 * 案件预警处理函数
 */
function handleRecWarn(self, data) {
    console.log("处理案件预警:", data);
    let recTypeStat1 = self.$$("csdn_page_indicator_8etrvm");
    let result1 = [
        {
            "name": "1",
            "value": "超期<10天",
            "text": data[0].greenWarn,
            "checked": false
        },
        {
            "name": "2",
            "text": data[0].blueWarn,
            "value": "超期>90天",
            "checked": false
        },
        {
            "name": "3",
            "text": data[0].yellowWarn,
            "value": "超期>120天",
            "checked": false
        }
    ];

    recTypeStat1.data.props.dataSource.options = result1 || [];

}


function getRecData(self, ddcatId, startTime, endTime, regionLevel, regionId) {
    var paramsValue = [
        { name: "startTime", valueContent: startTime },
        { name: "endTime", valueContent: endTime },
        { name: "regionType", valueContent: regionLevel },
        { name: "regionId", valueContent: regionId }
    ];

    return api.DATA_SOURCE_EXECUTE(ddcatId, "ddcat", paramsValue, [], "")
        .then(function (res) {
            if (!res.hasError) {
                return res.result;
            } else {
                return Promise.reject(res);
            }
        })
        .catch(function (err) {
            return Promise.reject(err);
        });
}
